package com.party.orders.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.party.alipay.AlipayRefundDTO;
import com.party.alipay.AlipayRefundVO;
import com.party.alipay.MyAlipayUtils;
import com.party.domain.CurrentAccount;
import com.party.domain.Refund;
import com.party.domain.ShopCart;
import com.party.dto.Page;
import com.party.exception.ExceptionMsgEnum;
import com.party.exception.ServiceException;
import com.party.orders.mapper.RefundMapper;
import com.party.orders.mapper.ShopCartMapper;
import com.party.orders.service.OrdersService;
import com.party.orders.service.RefundService;
import com.party.tool.OrdersNumUtils;

/**
 * 
 * @author Caizhf
 * @date 2017年8月15日下午3:16:59
 * @version v.0.1
 * @email 1115054416@qq.com
 *
 *        <p>
 *        Description:
 *        </p>
 *
 */
@Service
public class RefundServiceImpl implements RefundService {
	
	@Autowired
	private RefundMapper refundMapper;
	@Autowired
	private ShopCartMapper shopCartMapper;

	@Override
	@Transactional(readOnly=true)
	public Page list(Integer aid, Integer caid, int pageSize, int pageNum) {
		int totalRecord = refundMapper.CountList(aid,caid);
		Page page = new Page(totalRecord,pageNum,pageSize);
		List<Refund> refunds = refundMapper.list(aid,caid,page.getStartindex(),pageSize);
		page.setList(refunds);
		return page;
	}

	@Override
	public Refund findById(int rfid) {
		Refund rf = refundMapper.findById(rfid);
		return rf;
	}

	/*
	 * (non-Javadoc)
	 * @see com.party.orders.service.RefundService#execute(int, boolean, java.lang.String)
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void execute(int rfid, boolean isAgree, String refuseReason) {

		// 根据退款id级联查出订单、流水账
		Refund rf = refundMapper.findById(rfid);
		CurrentAccount ca = rf.getCurrentAccount();
		ShopCart sp = rf.getShopCart();
		if (rf == null || ca == null || sp == null||null==rf.getRefundNum()||null==rf.getRefundFee())
			throw new ServiceException(ExceptionMsgEnum.SERVER_DB_NOTEXIT);
		
		//如果同意退款，执行以下步骤
		if (isAgree) {
			try {
				// 从流水账中取出支付宝单号、流水单号，取出退款单号、退款原因、退款金额依次传入并执行alipay退款请求
				// 退款
				AlipayRefundVO refundVo = MyAlipayUtils.refund(ca.getAllOrderNum(), ca.getTradeNo(), rf.getRefundNum(),
						rf.getRefundFee().toString(), rf.getRefundReason());
				AlipayRefundDTO dto = refundVo.getAlipay_trade_refund_response();
				//如果支付宝退款接口调用成功，才执行业务逻辑
				if(dto.getCode().equals("10000")){
					// 修改退款表时间、退款所到支付宝账号
					refundMapper.refundResponseExecuteUpdate(dto.getGmt_refund_pay(), dto.getBuyer_logon_id(),rfid);
					// 修改清单状态为退款完成
					shopCartMapper.updateStateById(OrdersService.REFUNDED, sp.getSpid());
				}else{
				//支付宝接口调用退款失败（非程序异常原因失败导致出现的问题）
					//修改为失败状态
					shopCartMapper.updateStateById(OrdersService.REFUND_FAILURED, sp.getSpid());
					// 退款失败原因与状态码
					String failueReason = "支付宝调用问题：" + "\n错误代码：" + dto.getCode() + "\n错误描述："
							+ dto.getMsg() + "\n详情错误码：" + dto.getSub_code() + "\n详情错误信息"
							+ dto.getSub_msg();
					refundMapper.refundFailueredExcuteUpdate(failueReason,rfid);
				}
				
			} catch (Exception e) {
			/*	// 如果出现异常而失败，更新退款状态为失败
				shopCartMapper.updateStateById(OrdersService.REFUND_FAILURED, sp.getSpid());
				// 退款失败
				String failueReason = "支付宝接口调用出现本身程序异常问题！";
				refundMapper.refundFailueredExcuteUpdate(failueReason,rfid);
				e.printStackTrace();*/
				throw new ServiceException("支付宝接口调用出现本身程序异常问题！");
			}
		//如果不同意退款，执行以下步骤
		}else{
			//填写拒绝原因
			refundMapper.refundFailueredExcuteUpdate(refuseReason,rfid);
			//更新为退款失败
			shopCartMapper.updateStateById(OrdersService.REFUND_FAILURED, sp.getSpid());
		}
	}

	@Override
	public Refund findByShopCartId(int spid) {
		Refund rf =refundMapper.findByShopCartId(spid);
		return rf;
	}

	@Override
	public void delete(int rfid) {
		if(refundMapper.deleteById(rfid)==null)
			throw new ServiceException(ExceptionMsgEnum.SERVER_DB_NOTEXIT);
	}

	@Override
	public void update(String userRefundReason, String refuseReason, String refundFee,int rfid) {
		if(refundMapper.updateById(userRefundReason,refuseReason,refundFee,rfid)==null)
			throw new ServiceException(ExceptionMsgEnum.SERVER_DB_NOTEXIT);
	}
	

}
